const { app, BrowserWindow, screen, ipcMain, dialog } = require('electron');
const path = require('path');
const fs = require('fs').promises;
const https = require('https');

// 防止多实例
if (!app.requestSingleInstanceLock()) {
  app.quit();
}

let petWindow;
let settingsWindow;

// 配置文件
const CONFIG = {
  resourceUrl: 'https://gitee.com/xuxinzhi2206/my_pet/raw/master/', // 实际Gitee raw文件地址
  versionFile: 'version.json',
  resourceFiles: ['index.html', 'pet-script.js', 'pet-styles.css'] // 需要更新的文件
};

function createPetWindow() {
  try {
    const primaryDisplay = screen.getPrimaryDisplay();
    const { width, height } = primaryDisplay.workAreaSize;
    
    petWindow = new BrowserWindow({
      width: 160,
      height: 200,
      x: width - 180,
      y: height - 220,
      alwaysOnTop: true,
      skipTaskbar: true,
      frame: false,
      transparent: true,
      resizable: false,
      movable: true,
      minimizable: false,
      maximizable: false,
      closable: true,
      focusable: true,
      hasShadow: false,
      webPreferences: {
        nodeIntegration: true,
        contextIsolation: false,
        enableRemoteModule: true
      },
      show: false
    });

    petWindow.loadFile('index.html');

    petWindow.once('ready-to-show', () => {
      petWindow.show();
    });

    if (process.env.NODE_ENV === 'development') {
      petWindow.webContents.openDevTools({ mode: 'detach' });
    }

    petWindow.on('closed', () => {
      petWindow = null;
    });

    petWindow.webContents.setWindowOpenHandler(() => {
      return { action: 'deny' };
    });

  } catch (error) {
    console.error('创建宠物窗口失败:', error);
  }
}

function createSettingsWindow() {
  if (settingsWindow) {
    settingsWindow.focus();
    return;
  }

  settingsWindow = new BrowserWindow({
    width: 400,
    height: 500,
    parent: petWindow,
    modal: true,
    show: false,
    webPreferences: {
      nodeIntegration: true,
      contextIsolation: false
    },
    title: '设置',
    resizable: false
  });

  settingsWindow.loadFile('settings.html');

  settingsWindow.once('ready-to-show', () => {
    settingsWindow.show();
  });

  settingsWindow.on('closed', () => {
    settingsWindow = null;
  });
}

// 文件操作函数
async function readLocalVersion() {
  try {
    const versionPath = path.join(__dirname, 'version.json');
    const data = await fs.readFile(versionPath, 'utf8');
    return JSON.parse(data);
  } catch (error) {
    // 如果版本文件不存在，返回默认版本
    return { version: '1.0.0', buildDate: new Date().toISOString() };
  }
}

async function saveLocalVersion(versionInfo) {
  const versionPath = path.join(__dirname, 'version.json');
  await fs.writeFile(versionPath, JSON.stringify(versionInfo, null, 2));
}

// HTTP请求函数
function httpGet(url) {
  return new Promise((resolve, reject) => {
    https.get(url, (response) => {
      let data = '';
      
      response.on('data', (chunk) => {
        data += chunk;
      });
      
      response.on('end', () => {
        if (response.statusCode === 200) {
          resolve(data);
        } else {
          reject(new Error(`HTTP ${response.statusCode}`));
        }
      });
      
    }).on('error', (error) => {
      reject(error);
    });
  });
}

async function downloadFile(filename) {
  const url = `${CONFIG.resourceUrl}${filename}`;
  const data = await httpGet(url);
  const filePath = path.join(__dirname, filename);
  await fs.writeFile(filePath, data);
  return filePath;
}

// 检查资源文件更新
async function checkResourceUpdates() {
  try {
    // 读取远程版本信息
    const remoteVersionUrl = `${CONFIG.resourceUrl}${CONFIG.versionFile}`;
    const remoteVersionData = await httpGet(remoteVersionUrl);
    const remoteVersion = JSON.parse(remoteVersionData);
    
    // 读取本地版本信息
    const localVersion = await readLocalVersion();
    
    return {
      hasUpdate: remoteVersion.version !== localVersion.version,
      localVersion: localVersion.version,
      remoteVersion: remoteVersion.version,
      updateInfo: remoteVersion
    };
    
  } catch (error) {
    throw new Error(`检查更新失败: ${error.message}`);
  }
}

// 下载更新文件
async function downloadUpdates(progressCallback) {
  try {
    const totalFiles = CONFIG.resourceFiles.length;
    let completedFiles = 0;
    
    for (const filename of CONFIG.resourceFiles) {
      await downloadFile(filename);
      completedFiles++;
      
      if (progressCallback) {
        const progress = Math.round((completedFiles / totalFiles) * 100);
        progressCallback(progress, completedFiles, totalFiles, filename);
      }
    }
    
    // 更新本地版本文件
    const remoteVersionUrl = `${CONFIG.resourceUrl}${CONFIG.versionFile}`;
    const remoteVersionData = await httpGet(remoteVersionUrl);
    await saveLocalVersion(JSON.parse(remoteVersionData));
    
    return true;
    
  } catch (error) {
    throw new Error(`下载更新失败: ${error.message}`);
  }
}

// IPC 通信处理
ipcMain.handle('check-resource-updates', async () => {
  try {
    const updateInfo = await checkResourceUpdates();
    return { success: true, data: updateInfo };
  } catch (error) {
    return { success: false, error: error.message };
  }
});

ipcMain.handle('download-resource-updates', async (event, progressCallback) => {
  try {
    const progressHandler = (progress, completed, total, filename) => {
      event.sender.send('download-progress', { progress, completed, total, filename });
    };
    
    await downloadUpdates(progressHandler);
    return { success: true };
  } catch (error) {
    return { success: false, error: error.message };
  }
});

ipcMain.handle('get-app-version', async () => {
  const versionInfo = await readLocalVersion();
  return versionInfo.version;
});

ipcMain.handle('open-settings', () => {
  createSettingsWindow();
});

ipcMain.handle('restart-app', () => {
  dialog.showMessageBox(settingsWindow || petWindow, {
    type: 'info',
    title: '重启应用',
    message: '资源文件已更新，需要重启应用生效。是否立即重启？',
    buttons: ['立即重启', '稍后'],
    defaultId: 0
  }).then((result) => {
    if (result.response === 0) {
      app.relaunch();
      app.exit();
    }
  });
});

// Electron应用准备就绪
app.whenReady().then(() => {
  createPetWindow();
  
  app.on('activate', () => {
    if (BrowserWindow.getAllWindows().length === 0) {
      createPetWindow();
    }
  });
});

app.on('window-all-closed', () => {
  if (process.platform !== 'darwin') {
    app.quit();
  }
});

app.on('web-contents-created', (event, contents) => {
  contents.on('new-window', (event, navigationUrl) => {
    event.preventDefault();
  });
});